import React, {useEffect} from "react";
import {whiteRouteList} from "@/config/menu-config.ts";
import {useLocation, useNavigate} from "react-router-dom";
import {getToken, setToken} from "@/utils/Auth.ts";
import {notification} from "antd";
import {getMenus} from "@/utils/MuenUtils.tsx";

const PrivatePage: React.FC<{ children: React.ReactNode }> = ({children}) => {

  const navigate = useNavigate()
  const location = useLocation()
  const token = getToken()
  const menus = getMenus()

  const [notificationApi, contextHolder] = notification.useNotification();

  useEffect(() => {
    const {pathname} = location
    if (pathname === '/login' && token) {
      navigate('/home', {replace: true})
      return
    }
    if ((!token) && (!whiteRouteList.includes(pathname))) {
      notificationApi.error({
        message: '登陆失败',
        description: '您的登录信息已过期，请重新登录',
        key: "login-error"
      })
      navigate('/login')
    } else if ((!menus || menus.length <= 0) && pathname !== '/login') {
      setToken("")
      notificationApi.error({
        message: '用户数据异常',
        description: '您的登录信息已过期，请重新登录',
        key: "login-error"
      })
      navigate('/login')
    }
  }, [location.pathname])

  return (
    <div>
      {contextHolder}
      {children}
    </div>
  )
}

export default PrivatePage